package com.ncepu.clubmanagement.controller;

import com.ncepu.clubmanagement.exception.PasswordUnsafeException;
import com.ncepu.clubmanagement.pojo.PermissionOfThreeLevel;
import com.ncepu.clubmanagement.pojo.Person;
import com.ncepu.clubmanagement.pojo.PersonWithSchoolName;
import com.ncepu.clubmanagement.pojo.Result;
import com.ncepu.clubmanagement.service.PersonService;
import com.ncepu.clubmanagement.utils.JwtUtils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@Slf4j
@RestController
public class LoginController {

    @Autowired
    private PersonService personService;

    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping("/login")
    public Result login(@RequestBody Person person){


        Person result = personService.login(person);
        if (result == null){
            return Result.error("用户名或密码错误");
        }

        // 查询权限
        PermissionOfThreeLevel permission = personService.getPermissionOfThreeLevel(result.getId());

        log.info("{}登录成功",result.getAccount());


        // 生成jwt带有token
        String jwt = jwtUtils.generateJWT(new HashMap<>(){{
            put("account", result.getAccount());
            put("permission", permission.getPermissionLevel());  // 将权限一并放入jwt中
            put("id", result.getId());
        }});

        return Result.success(jwt);
    }

    @PostMapping("/register")
    public Result register(@RequestBody Person person) throws PasswordUnsafeException {
        personService.register(person);
        return Result.success();
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public Result handleDuplicateKeyException(DuplicateKeyException e){
        return Result.error("name repeat");
    }



}
